package com.zbdx.controller;

import com.google.gson.Gson;
import com.zbdx.domain.product;
import com.zbdx.service.IGoodsService;
import com.zbdx.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet(name = "ShopServlet", value = "/ShopServlet")
public class ShopServlet extends HttpServlet {
    IGoodsService goodsService = new GoodsServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("hello");
        System.out.println("hello");
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //2.获取请求参数
        String method = request.getParameter("method");
        System.out.println("method = "+ method);
        if("addGoods".equals(method)){
            try {
                this.addGoods(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("findAll".equals(method)) {
            try {
                this.findAll(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("removeById".equals(method)) {
            try {
                this.removeById(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("findByType".equals(method)) {
            try {
                this.findByType(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("findById".equals(method)) {
            try {
                this.findById(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        } else if ("search".equals(method)) {
            try {
                this.search(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("modifyGoods".equals(method)) {
            try {
                this.modifyGoods(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if ("removeSelect".equals(method)) {
            try {
                this.removeSelect(request,response);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else{
            System.out.println("请求地址有误");
        }
    }

    private void removeSelect(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String[] ids = request.getParameterValues("ids[]");
        System.out.println("ids = " + ids);
        if (ids != null) {
            List<Integer> idList = Arrays.stream(ids).map(Integer::parseInt).collect(Collectors.toList());
            boolean flag = goodsService.removeSelect(idList);
            if(flag) response.getWriter().print(1);
            else response.getWriter().print(0);
        } else {
            response.getWriter().print(0);
        }
    }

    private void modifyGoods(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        Gson gson = new Gson();
        //将JSON字符串转换为User对象
        String data = request.getParameter("data");
        System.out.println(data);

        product product = gson.fromJson(data, com.zbdx.domain.product.class);
        boolean flag = goodsService.modifyGoods(product);
        PrintWriter write = response.getWriter();
        if(flag){
            write.print(1);
        }else{
            write.print(0);
        }
        write.close();
    }

    private void findById(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        String id = request.getParameter("PId");
        String flag = request.getParameter("flag");
        int Flag = Integer.parseInt(flag);
        System.out.println("PId: "+id);
        if(id!=null){
            int PId = Integer.parseInt(id);
            product product = goodsService.findById(PId);
            //获取session
            HttpSession session = request.getSession();
            //将User对象放到会话session域共享
            session.setAttribute("Product",product);
            //转发到修改页面(editUser.jsp)

            if(Flag==1){
                request.getRequestDispatcher("page/shopping/merchant/editGoods.jsp").forward(request,response);
            }else{
                request.getRequestDispatcher("page/shopping/merchant/GoodsDetail.jsp").forward(request,response);
            }

        }else{
            System.out.println("商品ID为空");
        }
    }

    private void search(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        System.out.println("hellosearch");
//        String searchParams = request.getParameter("searchParams");
//        System.out.println(searchParams);
//        Gson gson1 = new Gson();
//        product P = gson1.fromJson(searchParams, product.class);
//        System.out.println(P);
        String Id = request.getParameter("PId");
        String PName = request.getParameter("PName");
        String PType = request.getParameter("PType");

        System.out.println(PName+" "+PType+" "+Id);

        List<product> list = goodsService.search(PName,PType,Id);
        //使用哈希表存储数据
        HashMap<String,Object> map = new LinkedHashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",100);
        map.put("data",list);
        System.out.println(map);
        //将map转换为JSON对象
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json="+json);
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.close();
    }

    private void findByType(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String PType = request.getParameter("PType");
        System.out.println("PType");
        List<product> list = goodsService.findByType(PType);
        //使用哈希表存储数据
        HashMap<String,Object> map = new LinkedHashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",100);
        map.put("data",list);
        System.out.println(map);
        //将map转换为JSON对象
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json="+json);
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.close();
    }

    private void removeById(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String id = request.getParameter("PId");
        System.out.println("id : "+ id);
        if(id!=null){
            //将字符串id转换成整数
            int PId = Integer.parseInt(id);
            //调用业务层根据ID删除的方法
            boolean flag = goodsService.removeById(PId);
            PrintWriter writer = response.getWriter();
            if(flag){
                writer.print(1);
            }else{
                writer.print(0);
            }
        }else{
            System.out.println("商品ID为空");
        }
    }

    private void findAll(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        List<product> list = goodsService.findAll();
        //使用哈希表存储数据
        HashMap<String,Object> map = new LinkedHashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",100);
        map.put("data",list);
        System.out.println(map);
        //将map转换为JSON对象
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json="+json);
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.close();
    }

    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        //将JSON字符串转换为User对象
        String data = request.getParameter("data");
        System.out.println(data);

        Gson gson = new Gson();
        product product = gson.fromJson(data, com.zbdx.domain.product.class);
//        IGoodsService goodsService = new GoodsServiceImpl();
        boolean flag = goodsService.addGoods(product);
        PrintWriter write = response.getWriter();
        if(flag){
            write.print(1);
        }else{
            write.print(0);
        }
        write.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
